<template>
  <div class="tab-content">
    <div class="header-section">
      <div class="title-section">
        <h2>功图数据分析</h2>
        <span class="subtitle">查看和分析功图采集数据</span>
      </div>

     <div class="action-section">
        <el-date-picker
          v-model="selectedDate"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
          :loading="loadingTimes"
          clearable
          class="time-select-item"
        />
        <el-select
          v-model="selectedHour"
          placeholder="选择小时"
          @change="handleHourChange"
          clearable
          class="time-select-item"
        >
          <el-option
            v-for="hour in availableHours"
            :key="hour.value"
            :label="hour.label"
            :value="hour.value"
          />
        </el-select>
        <el-select
          v-model="selectedTime"
          placeholder="选择具体时间"
          @change="handleTimeChange"
          clearable
          class="time-select-item"
        >
          <el-option
            v-for="time in availableTimes"
            :key="time.value"
            :label="formatMinuteSecond(time.value)"
            :value="time.value"
          />
        </el-select>
        
        <el-button type="primary" @click="fetchCollectionTimes">
          <el-icon><Refresh /></el-icon>刷新时间列表
        </el-button>
        <el-button type="success" @click="handleExportChart">
          <el-icon><Download /></el-icon>导出
        </el-button>
      </div>
    </div>
    
    <el-card class="chart-card" :body-style="{ padding: '10px' }">
      <div class="chart-wrapper" v-loading="loadingChart">
        <D3ChartGraph 
          :key="currentDevice + '_' + chartUpdateKey"
          :data="chartData" 
          :currentDevice="currentDevice"
          :xRange="[adjustedXMin, adjustedXMax]"
          height="300px" 
        />
      </div>
    </el-card>

    <el-card class="data-card" :body-style="{ padding: '0' }">
      <template #header>
        <div class="card-header">
          <span>功图数据详情</span>
        </div>
      </template>
      <el-table 
        :data="tableData" 
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
        border
        stripe
        highlight-current-row
      >
        <el-table-column prop="point" label="功图点数" width="100" />
        <el-table-column prop="time" label="采集时间" width="180" />
        <el-table-column 
          prop="x" 
          label="位移 (m)" 
          :formatter="(row) => row.x.toFixed(2)"
        />
        <el-table-column 
          prop="y" 
          label="载荷 (kN)" 
          :formatter="(row) => row.y.toFixed(2)"
        />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import D3ChartGraph from '../D3ChartGraph.vue'
import { Download } from '@element-plus/icons-vue'

const props = defineProps({
  currentDevice: {
    type: Object,
    required: true
  }
})

// 功图数据相关
const chartData = ref([]);
const tableData = ref([]);
const loadingChart = ref(false);
const loadingTimes = ref(false);
const chartUpdateKey = ref(0); // 用于强制更新图表的key
const adjustedXMin = ref(0);
const adjustedXMax = ref(0);
const collectionTimes = ref([]);
const selectedDate = ref('');
const selectedHour = ref('');
const selectedTime = ref('');
const availableHours = ref([]);
const availableTimes = ref([]);

// 格式化时间显示
const formatTime = (time) => {
  if (!time) return '';
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 格式化日期（仅显示年月日）
const formatDateLocal = (time) => {
  if (!time) return '';
  return new Date(time).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

// 格式化小时（仅显示小时）
const formatHour = (time) => {
  if (!time) return '';
  return new Date(time).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    hour12: false
  });
};

// 格式化为完整时间（显示年月日时分秒）
const formatMinuteSecond = (time) => {
  if (!time) return '';
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

// 处理时间数据
const processTimeData = () => {
  if (!collectionTimes.value || collectionTimes.value.length === 0) {
    selectedDate.value = '';
    selectedHour.value = '';
    selectedTime.value = '';
    availableHours.value = [];
    availableTimes.value = [];
    return;
  }

  // 如果没有选择日期，默认选择最新的日期
  if (!selectedDate.value && collectionTimes.value.length > 0) {
    const latestTime = collectionTimes.value[0];
    selectedDate.value = dayjs(latestTime).format('YYYY-MM-DD');
    handleDateChange(selectedDate.value);
  }
};

// 处理日期变化
const handleDateChange = (date) => {
  selectedHour.value = '';
  selectedTime.value = '';
  availableHours.value = [];
  availableTimes.value = [];
  
  if (!date) {
    return;
  }

  // 获取选中日期的所有时间点
  const dayTimes = collectionTimes.value.filter(time => 
    dayjs(time).format('YYYY-MM-DD') === date
  );

  // 按小时分组
  const hourMap = new Map();
  dayTimes.forEach(time => {
    const hour = dayjs(time).format('HH');
    if (!hourMap.has(hour)) {
      hourMap.set(hour, []);
    }
    hourMap.get(hour).push(time);
  });

  // 转换为选择器选项格式
  availableHours.value = Array.from(hourMap.entries())
    .sort((a, b) => b[0].localeCompare(a[0]))
    .map(([hour, times]) => ({
      label: `${hour}时 (${times.length}项)`,
      value: hour
    }));

  // 如果有数据，默认选择第一个小时
  if (availableHours.value.length > 0) {
    selectedHour.value = availableHours.value[0].value;
    handleHourChange(selectedHour.value);
  }
};

// 处理小时变化
const handleHourChange = (hour) => {
  selectedTime.value = '';
  availableTimes.value = [];
  
  if (!hour || !selectedDate.value) {
    return;
  }

  // 获取选中日期和小时的所有时间点
  const hourTimes = collectionTimes.value.filter(time => {
    const timeObj = dayjs(time);
    return timeObj.format('YYYY-MM-DD') === selectedDate.value && 
           timeObj.format('HH') === hour;
  });

  // 转换为选择器选项格式，确保时间格式正确
  availableTimes.value = hourTimes
    .sort((a, b) => new Date(b) - new Date(a))
    .map(time => {
      const date = new Date(time);
      return {
        label: formatMinuteSecond(time),
        value: date.toISOString() // 存储为ISO格式
      };
    });

  // 如果有数据，默认选择第一个时间点
  if (availableTimes.value.length > 0) {
    selectedTime.value = availableTimes.value[0].value;
    handleTimeChange(selectedTime.value);
  }
};

// 分页加载时间选项
const loadPagedTimeOptions = (times, pageSize = 1000) => {
  if (times.length <= pageSize) {
    // 如果时间点数量不多，直接返回所有时间点
    return times.map(time => ({
      label: formatMinuteSecond(time),
      value: time,
      leaf: true
    }));
  }
  
  // 计算需要的页数
  const totalPages = Math.ceil(times.length / pageSize);
  
  // 创建分页选项
  return Array.from({ length: totalPages }, (_, i) => {
    const start = i * pageSize;
    const end = Math.min(start + pageSize, times.length);
    return {
      label: `第${i + 1}页 (${start + 1}-${end}项)`,
      value: `page_${i}`,
      children: times.slice(start, end).map(time => ({
        label: formatMinuteSecond(time),
        value: time,
        leaf: true
      }))
    };
  });
};

// 获取更多时间点数据
const fetchMoreTimes = async (deviceNumber, totalCount) => {
  try {
    const token = localStorage.getItem('token');
    const batchSize = 2000; // 增加每批获取的数据量
    const batches = Math.ceil(totalCount / batchSize);
    let allTimes = [];
    
    // 显示加载进度
    const loadingInstance = ElMessage({
      type: 'info',
      message: '正在加载时间数据，请稍候...',
      duration: 0,
      showClose: true
    });
    
    for (let i = 1; i <= batches; i++) {
      const response = await fetch(`https://penglink.pcwxcn.top/api/dashboard/times/limit/${deviceNumber}?limit=20000`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      });
      
      if (!response.ok) continue;
      
      const result = await response.json();
      if (result.code === 200 && result.data.times) {
        allTimes = [...allTimes, ...result.data.times];
        
        // 更新加载进度消息
        if (loadingInstance) {
          loadingInstance.message = `正在加载时间数据 (${allTimes.length}/${totalCount})...`;
        }
      }
      
      // 如果已经获取了所有时间点，提前结束循环
      if (allTimes.length >= totalCount) break;
    }
    
    // 关闭加载提示
    if (loadingInstance) {
      loadingInstance.close();
    }
    
    if (allTimes.length > 0) {
      // 按时间降序排序
      allTimes.sort((a, b) => new Date(b) - new Date(a));
      collectionTimes.value = allTimes;
      
      // 处理时间数据
      processTimeData();
      
      ElMessage.success(`成功加载 ${allTimes.length} 个时间点数据`);
    } else {
      ElMessage.warning('没有找到时间点数据');
    }
  } catch (error) {
    ElMessage.error('获取时间点数据失败: ' + error.message);
  }
};

// 处理时间选择变化
const handleTimeChange = (value) => {
  if (value) {
    // 将时间转换为RFC3339格式
    const date = new Date(value);
    const rfc3339Time = date.toISOString();
    selectedTime.value = rfc3339Time;
    fetchChartData();
  }
};

// 获取功图采集时间列表
const fetchCollectionTimes = async () => {
  if (!props.currentDevice) {
    ElMessage.warning('请先选择设备');
    return;
  }
  loadingTimes.value = true;
  try {
    const token = localStorage.getItem('token');
    // 直接使用设备ID
    const deviceNumber = props.currentDevice.id; 
    if (!deviceNumber) {
      throw new Error('无效的设备ID');
    }
    
    // 第一次请求获取总数量
    const initialResponse = await fetch(`https://penglink.pcwxcn.top/api/dashboard/times/${deviceNumber}?page=1&page_size=100?limit=20000`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    });
    
    if (!initialResponse.ok) {
      throw new Error('获取时间列表失败');
    }
    
    const initialResult = await initialResponse.json();
    if (initialResult.code === 200) {
      // 获取总时间点数量
      const totalTimePoints = initialResult.data.count || 0;
      
      // 如果总数量大于初始加载的数量，则获取所有数据
      if (totalTimePoints > 0) {
        ElMessage.info(`正在加载全部${totalTimePoints}个时间点数据...`);
        
        // 直接获取所有时间点
        await fetchMoreTimes(deviceNumber, totalTimePoints);
      } else {
        ElMessage.warning('没有找到时间点数据');
        collectionTimes.value = [];
        processTimeData();
      }
    } else {
      throw new Error(initialResult.message || '获取时间列表失败');
    }
  } catch (error) {
    ElMessage.error(error.message);
    collectionTimes.value = [];
    processTimeData();
  } finally {
    loadingTimes.value = false;
  }
};

// 获取功图数据
const fetchChartData = async () => {
  if (!props.currentDevice) {
    ElMessage.warning('请先选择设备')
    return
  }
  loadingChart.value = true
  try {
    const token = localStorage.getItem('token')
    // 直接使用设备ID
    const deviceNumber = props.currentDevice.id; 
    if (!deviceNumber) {
      throw new Error('无效的设备ID')
    }
    // 构建URL，使用RFC3339格式的时间
    let url = `https://penglink.pcwxcn.top/api/dashboard/chart/time/${deviceNumber}`
    if (selectedTime.value) {
      // 确保时间格式符合RFC3339标准
      url += `?time=${encodeURIComponent(selectedTime.value)}`
    }
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    if (!response.ok) {
      throw new Error('获取数据失败')
    }
    const result = await response.json()
    
    if (result.code === 200) {
      // 从嵌套的chart_data中获取数据
      const { chart_data = {} } = result.data
      const { points = [], times = [], x = [], y = [] } = chart_data
      
      // 获取点数限制
      const pointLimit = parseInt(points[0]) || 0
      
      // 确保数据是数字类型并限制点数，同时将数据除以100并保留两位小数
      // 不再反转数组，保持原始顺序，确保X轴时间按照从小到大从左向右排列
      const xValues = [...x].slice(0, pointLimit).map(val => Number((parseFloat(val) / 100).toFixed(2)))
      const yValues = [...y].slice(0, pointLimit).map(val => Number((parseFloat(val) / 100).toFixed(2)))
      
      // 计算数据范围
      const xMin = Math.min(...xValues)
      const xMax = Math.max(...xValues)
      const yMin = Math.min(...yValues)
      const yMax = Math.max(...yValues)
      
      // 计算X轴的合适范围
      const xRange = xMax - xMin
      const xPadding = xRange * 0.1 // 10% 的padding
      adjustedXMin.value = Math.max(0, xMin - xPadding)
      adjustedXMax.value = xMax + xPadding

      // 确保数据有效
      if (xValues.length > 0 && yValues.length > 0) {
        // 更新图表数据
        chartData.value = xValues.map((xValue, index) => [xValue, yValues[index]])
        
        // 更新表格数据
        tableData.value = Array.from({ length: Math.min(pointLimit, xValues.length) }, (_, index) => {
          // 直接使用API返回的时间
          const displayTime = times[index] || '';
          
          return {
            point: index + 1,
            time: displayTime,
            x: xValues[index] || 0,
            y: yValues[index] || 0
          };
        })

        // 增加key值触发图表重新渲染
        chartUpdateKey.value++
      } else {
        ElMessage.warning('获取到的数据为空或无效')
        chartData.value = []
        tableData.value = []
      }
    } else {
      throw new Error(result.message || '获取功图数据失败')
    }
  } catch (error) {
    ElMessage.error(error.message)
    chartData.value = []
    tableData.value = []
  } finally {
    loadingChart.value = false
  }
}

// 导出按钮处理函数
const handleExportChart = () => {
  ElMessage.info('导出功能开发中...')
}

// 监听设备变化
watch(() => props.currentDevice, (newDevice) => {
  if (newDevice) {
    fetchCollectionTimes();
  }
}, { immediate: true })

// 生命周期钩子
onMounted(async () => {
  if (props.currentDevice) {
    await fetchCollectionTimes();
  }
})
</script>

<style scoped>
.tab-content {
  margin-top: 20px;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-section h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.title-section .subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
  display: block;
}

.action-section {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.time-select-item {
  min-width: 180px;
  max-width: 220px;
  flex: 1;
}

.action-section {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
  margin: 16px 0;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6;
  transition: all 0.2s;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--el-color-primary);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) !important;
}

:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-color-primary) !important;
}

@media screen and (max-width: 768px) {
  .time-select-item {
    min-width: 100%;
    max-width: 100%;
  }
  
  .action-section {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
}

.chart-card {
  margin-bottom: 16px;
}

.chart-wrapper {
  width: 100%;
  height: 100%;
  background: white;
  padding: 10px;
  border-radius: 8px;
}

.data-card {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  background: #ffffff;
}

:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
  --el-table-border-color: #e4e7ed;
  --el-table-header-text-color: #606266;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}
</style>